<script>
import BookForm from "../../components/book/BookForm.vue";
import BookApi from "../../api/book";

export default {
  components: {
    BookForm
  },
  data() {
    return {
      book: {}
    };
  },
  methods: {
    async getBook(bookId) {
      try {
        const api = new BookApi();
        let res = await api.find(bookId);
        this.book = res.data;
        console.log(this.book);
      } catch (err) {
        console.error(err);
        this.$myMessageBox("应用服务器访问错误！");
      }
    },
    async bookSave() {
      if (this.book.title && this.book.isbn) {
        try {
          const api = new BookApi();
          let res = await api.edit(this.book);
          console.log(res);
          if (res.code === 200) {
            this.$myMessageBox(res.msg);
            this.$router.push({ name: "book-list" });
          }
        } catch (err) {
          console.error(err);
          this.$myMessageBox("应用服务器访问错误！");
        }
      } else {
        this.$myMessageBox("书名与ISBN号信息不完整！");
      }
    }
  },
  mounted() {
    let bookId = this.$route.params.id;
    let book = JSON.parse(sessionStorage.getItem(`book-${bookId}`));
    if (book.id === bookId) {
      this.book = book;
    } else {
      this.getBook(bookId);
    }
  }
};
</script>

<template>
  <div class="book-edit w80">
    <div class="header">
      <h2>编辑书籍</h2>
      <p>
        <a class="button" href="javascript:void(0)" @click="$goBack">返回</a>
      </p>
    </div>
    <div class="block">
      <book-form v-model="book" @book-save="bookSave"></book-form>
    </div>
  </div>
</template>

<style scoped></style>
